package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * 查询文档
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-29
 */
public class TermQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(TermQuery.class);

    /**
     * term查询
     */
    @Test
    public void termQuery() throws IOException {
        // 创建searchRequest对象
        SearchRequest searchRequest = new SearchRequest(EsConfig.INDEX_NAME);
        // 指定查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(100);
        searchSourceBuilder.query(QueryBuilders.termQuery("name.keyword", "张三1"));
        searchRequest.source(searchSourceBuilder);
        SearchResponse res = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : res.getHits().getHits()) {
            Map<String, Object> result = hit.getSourceAsMap();
            logger.info(result.toString());
        }
    }

    /**
     * terms 查询
     */
    @Test
    public void termsQuery() throws IOException {
        // 创建查询对象
        SearchRequest searchRequest = new SearchRequest(EsConfig.INDEX_NAME);
        // 查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(20);
        searchSourceBuilder.query(QueryBuilders.termsQuery("name.keyword", "张三1", "张三2", "张三"));
        searchRequest.source(searchSourceBuilder);
        // 执行查询
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : search.getHits().getHits()) {
            Map<String, Object> map = hit.getSourceAsMap();
            logger.info("输出结果：{}", map.toString());
        }
    }
}
